package com.ruoyi.gigi.record.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.fastjson2.util.DateUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gigi.course.domain.Course;
import com.ruoyi.gigi.course.service.ICourseService;
import com.ruoyi.gigi.enums.SignInRecordStateEnum;
import com.ruoyi.gigi.enums.SignInTypeEnum;
import com.ruoyi.gigi.gigi_class.service.IGigiClassService;
import com.ruoyi.gigi.record.domain.SignInRecord;
import com.ruoyi.gigi.record.service.ISignInRecordService;
import com.ruoyi.gigi.sign.domain.SignIn;
import com.ruoyi.gigi.sign.service.ISignInService;
import com.ruoyi.gigi.user.domain.User;
import com.ruoyi.gigi.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 考勤记录管理Controller
 *
 * @author gigi
 * @date 2024-01-31
 */
@RestController
@RequestMapping("/gigi.record/record")
public class SignInRecordController extends BaseController {
    @Autowired
    private ISignInRecordService signInRecordService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IGigiClassService classService;
    @Autowired
    private ISignInService signInService;
    @Autowired
    private ICourseService courseService;

    /**
     * 查询考勤记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(SignInRecord signInRecord) {
        startPage();
        List<SignInRecord> list = signInRecordService.selectSignInRecordList(signInRecord);
        for (int i = 0; i < list.size(); i++) {
            User user = userService.selectUserById(list.get(i).getUserId());
            if (Objects.isNull(user)) {
                list.remove(i);
            } else {
                list.get(i).setUserName(user.getName());
                list.get(i).setUserNo(user.getNo());
                list.get(i).setSignInTimeStr(DateUtils.format(list.get(i).getSignInTime(), "yyyy-MM-dd HH:mm:ss"));
                list.get(i).setStateDesc(SignInRecordStateEnum.getEnumByCode(list.get(i).getState()).getDesc());
                list.get(i).setUserClass(classService.selectGigiClassById(user.getClassId()).getName());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出考勤记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:export')")
    @Log(title = "考勤记录管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SignIn signIn) {
        // 准备数据

        // 签到信息
        SignIn signIn1 = signInService.selectSignInById(signIn.getId());
        Course course = courseService.selectCourseById(signIn1.getCourseId());
        User user = userService.selectUserById(signIn1.getUserId());
        signIn1.setUserName(user.getName());
        signIn1.setUserNo(user.getNo());
        signIn1.setCourseName(course.getName() + '(' + course.getNo() + ')');
        signIn1.setTypeDesc(SignInTypeEnum.getEnumByCode(signIn1.getType()).getDesc());
        signIn1.setStartTimeStr(DateUtils.format(signIn1.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
        signIn1.setEndTimeStr(DateUtils.format(signIn1.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        List<String> classes = Arrays.stream(StringUtils.split(course.getClassId(), ",")).collect(Collectors.toList());
        List<String> classNames = classes.stream().map(i -> {
            return classService.selectGigiClassById(Long.valueOf(i)).getName();
        }).collect(Collectors.toList());
        signIn1.setClassName(org.apache.commons.lang3.StringUtils.join(classNames, ","));

        // 考勤列表
        SignInRecord signInRecord = new SignInRecord();
        signInRecord.setSignInId(signIn1.getId());
        List<SignInRecord> signInRecords = signInRecordService.selectSignInRecordList(signInRecord);
        for (int i = 0; i < signInRecords.size(); i++) {
            User userEntity = userService.selectUserById(signInRecords.get(i).getUserId());
            if (Objects.isNull(userEntity)) {
                signInRecords.remove(i);
            } else {
                signInRecords.get(i).setUserName(userEntity.getName());
                signInRecords.get(i).setUserNo(userEntity.getNo());
                signInRecords.get(i).setSignInTimeStr(DateUtils.format(signInRecords.get(i).getSignInTime(), "yyyy-MM-dd HH:mm:ss"));
                signInRecords.get(i).setStateDesc(SignInRecordStateEnum.getEnumByCode(signInRecords.get(i).getState()).getDesc());
                signInRecords.get(i).setUserClass(classService.selectGigiClassById(userEntity.getClassId()).getName());
            }
        }

        // 创建一个excel
        String fileName = "/Users/zhangyingying/Desktop/考勤统计.xlsx"; // 写想生成文件的路径

        // 向excel中写数据
        ExcelWriter excelWriter = EasyExcel.write(fileName).build();
        WriteSheet writeSheet = EasyExcel.writerSheet("考勤统计").needHead(Boolean.FALSE).build();
        WriteTable writeTable0 = EasyExcel.writerTable(0).head(SignIn.class).needHead(Boolean.TRUE).build();
        WriteTable writeTable1 = EasyExcel.writerTable(1).head(SignInRecord.class).needHead(Boolean.TRUE).build();
        excelWriter.write(Collections.singletonList(signIn1), writeSheet, writeTable0);
        excelWriter.write(signInRecords, writeSheet, writeTable1);
        excelWriter.finish();
    }

    /**
     * 获取考勤记录管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(signInRecordService.selectSignInRecordById(id));
    }

    /**
     * 新增考勤记录管理
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:add')")
    @Log(title = "考勤记录管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SignInRecord signInRecord) {
        return toAjax(signInRecordService.insertSignInRecord(signInRecord));
    }

    /**
     * 修改考勤记录管理
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:edit')")
    @Log(title = "考勤记录管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SignInRecord signInRecord) {
        return toAjax(signInRecordService.updateSignInRecord(signInRecord));
    }

    /**
     * 删除考勤记录管理
     */
    @PreAuthorize("@ss.hasPermi('gigi.record:record:remove')")
    @Log(title = "考勤记录管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(signInRecordService.deleteSignInRecordByIds(ids));
    }
}
